//
//  GMForgotVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/7/9.
//  Copyright © 2018年 小熊. All rights reserved.
//

#import "GMForgotVC.h"
#define TIMECOUNT 60
@interface GMForgotVC ()
@property (weak, nonatomic) IBOutlet UITextField *accountTF;
@property (weak, nonatomic) IBOutlet UITextField *verCodeTF;
@property (weak, nonatomic) IBOutlet UITextField *pwdTF;
@property (weak, nonatomic) IBOutlet UIButton *verBtn;

@end

@implementation GMForgotVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"找回密码";
}
/**获取验证码*/
- (IBAction)verCodeBtnClick:(UIButton *)sender {
    if (kIsEmptyString(self.accountTF.text)) {
        [MBProgressHUD showErrorOrSuc:@"请输入手机号码" toView:self.view];
        return;
    }
    /**验证手机号码是否正确*/
    if (![NSString zj_isMobilePhone:self.accountTF.text]) {
        [MBProgressHUD showErrorOrSuc:@"请输入正确的账号" toView:self.view];
        return;
    }
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"mobileCode":self.accountTF.text,
                          @"temp":@"2"
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"do-api.ashx?$m=SendVerifyCode&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                __block NSInteger second = TIMECOUNT;
                //(1)
                dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                //(2)
                dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
                //(3)
                dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
                //(4)
                dispatch_source_set_event_handler(timer, ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (second == 0) {
                            self.verBtn.userInteractionEnabled = YES;
                            [self.verBtn setTitle:[NSString stringWithFormat:@"验证码"] forState:UIControlStateNormal];
                            second = TIMECOUNT;
                            //(6)
                            dispatch_cancel(timer);
                        } else {
                            self.verBtn.userInteractionEnabled = NO;
                            [self.verBtn setTitle:[NSString stringWithFormat:@"%ld",second] forState:UIControlStateNormal];
                            second--;
                        }
                    });
                });
                //(5)
                dispatch_resume(timer);
            }else{
                /**显示错误信息*/
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
            
        }else{
            NSLog(@"%@",error);
        }
    }];
    
}
/**重置密码*/
- (IBAction)makeSureBtnClick:(id)sender {
    if (kIsEmptyString(self.accountTF.text)) {
        [MBProgressHUD showErrorOrSuc:@"请输入手机号码" toView:self.view];
        return;
    }
    /**验证手机号码是否正确*/
    if (![NSString zj_isMobilePhone:self.accountTF.text]) {
        [MBProgressHUD showErrorOrSuc:@"请输入正确的账号" toView:self.view];
        return;
    }
    if (kIsEmptyString(self.verCodeTF.text)) {
        [MBProgressHUD showErrorOrSuc:@"请输入验证码" toView:self.view];
        return;
    }
    if (kIsEmptyString(self.pwdTF.text)) {
        [MBProgressHUD showErrorOrSuc:@"请输入密码" toView:self.view];
        return;
    }
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"mobileCode":self.accountTF.text,
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"password":self.pwdTF.text,
                          @"verifyCode":self.verCodeTF.text
                          };
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"do-api.ashx?$m=ResetPassword&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [MBProgressHUD showErrorOrSuc:@"密码设置成功" toView:self.view];
//                NSDictionary *dict = [responseObject objectForKey:RESULT_NAME_Data];
                /**延迟两秒之后跳转到登录页面*/
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
                
            }else{
                /**显示错误信息*/
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:self.view];
            }
        }else{
            NSLog(@"%@",error);
        }
    }];
    
}
/**密码明文和密文*/
- (IBAction)lookPwdBtnClcik:(id)sender {
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:self.accountTF]) {
        NSString *phoneStr = [NSString stringWithFormat:@"%@%@", textField.text, string];
        if ([phoneStr length] > 11 && ![string isEqualToString:@""]) {
            textField.text = [phoneStr substringToIndex:11];
            return NO;
        }
    }
    if ([textField isEqual:self.verCodeTF]) {
        NSString *verStr = [NSString stringWithFormat:@"%@%@", textField.text, string];
        if ([verStr length] > 6 && ![string isEqualToString:@""]) {
            textField.text = [verStr substringToIndex:6];
            return NO;
        }
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
